package filelisting

import (
	"fmt"
	"github.com/gpmgo/gopm/modules/log"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

type userError string

func (e userError) Error() string {
	return e.Message()
}

func (e userError) Message() string {
	return string(e)
}

const prefix = "/list/"

func HandlerFileList(writer http.ResponseWriter, r *http.Request) error{
	if strings.Index(r.URL.Path, prefix) != 0 {
		//return errors.New("path must start with " + prefix)
		return userError("path must start with " + prefix)
	}
	path := r.URL.Path[len(prefix):]
	fmt.Printf("%s\n", path)
	log.Debug("%s", path)
	file, err := os.Open(path)
	if err != nil {
		//panic(err)
		//缺点：向用户展示了内部逻辑
		//http.Error(writer, err.Error(), http.StatusInternalServerError)
		return err
	}

	defer file.Close()
	all, err := ioutil.ReadAll(file)
	if err != nil {
		//panic(err)
		return err
	}

	writer.Write(all)

	return nil
}
